#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Source:
 http://blog.notdot.net/2010/03/Implementing-a-dropbox-service-with-the-Blobstore-API-Part-1, 
 Saved nik1.py
""" 

import cgi
import datetime
import urllib
import webapp2

import jinja2
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import users

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import util


class FileInfo(db.Model):
  blob = blobstore.BlobReferenceProperty(required=True)
  uploaded_by = db.UserProperty(required=True)
  uploaded_at = db.DateTimeProperty(required=True, auto_now_add=True)


class FileUploadFormHandler(webapp2.RequestHandler):
  @util.login_required
  def get(self):
    template_values = {
            'form_url': blobstore.create_upload_url('/upload'),
            'logout_url': users.create_logout_url('/'),
    }
    template = jinja_environment.get_template('upload1.html')
    self.response.out.write(template.render(template_values))


class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    blob_info = self.get_uploads()[0]
    if not users.get_current_user():
      blob_info.delete()
      self.redirect(users.create_login_url("/"))
      return

    file_info = FileInfo(blob=blob_info.key(),
                         uploaded_by=users.get_current_user())
    db.put(file_info)
    self.redirect("/file/%d" % (file_info.key().id(),)) 


class FileInfoHandler(webapp2.RequestHandler):
  def get(self, file_id):
    file_info = FileInfo.get_by_id(long(file_id))
    if not file_info:
      self.error(404)
      return
    template_values = {
            'file_info': file_info,
            'logout_url': users.create_logout_url('/'),
    }
    template = jinja_environment.get_template('info1.html')
    self.response.out.write(template.render(template_values))


class FileDownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, file_id):
    file_info = FileInfo.get_by_id(long(file_id))
    if not file_info or not file_info.blob:
      self.error(404)
      return
    self.send_blob(file_info.blob, save_as=True)


app = webapp2.WSGIApplication([('/', FileUploadFormHandler),
                                      ('/upload', FileUploadHandler),
                                      ('/file/([0-9]+)', FileInfoHandler),
                                      ('/file/([0-9]+)/download', FileDownloadHandler)],
                                     debug=True) 
